package com.training.food.controller;

import com.training.food.Mapper.RecordinfoMapper;
import com.training.food.pojo.User;
import com.training.food.util.CommonResult;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/upload")
public class FileUpLoad {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RecordinfoMapper recordinfoMapper;

    @PostMapping("/picture")
    public CommonResult upLoadPicture(HttpServletRequest request, @RequestParam("pictureFile") MultipartFile pictureFile) {
        if (pictureFile.isEmpty()) {
            return CommonResult.failed("请选择文件");
        }
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Object obj = redisTemplate.opsForValue().get((String) request.getAttribute("token"));
        System.out.println(request.getAttribute("token").toString());
        User user = (User) obj;
        String fileURI = "images/"+user.getUsername() + ft.format(new Date()) + ".jpg";
        String fileRoot = "/Users/zhangzhimin/Desktop/实训资料与成果/food-project/food/src/main/resources/static/";
        File keepFile = new File(fileRoot + fileURI);
        try {
            pictureFile.transferTo(keepFile);
            System.out.println("OK!   " + keepFile.getAbsolutePath());
            return CommonResult.success(fileURI);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.failed("系统原因上传失败，请再次尝试！");
    }
}